<template>
  <view class="join-shop-container">
    <!-- 表单内容区域 -->
    <view class="form-container">
      <u--form
          :model="formData"
          ref="form"
          :rules="rules"
          labelPosition="left"
          labelWidth="140"
      >
        <!-- 店铺名称 -->
        <u-form-item label="店铺名称" prop="company" required borderBottom label-width="200">
          <u--input
              v-model="formData.company"
              placeholder="请输入店铺名称"
              border="none"
              clearable
              :disabled="viewOnly"
          ></u--input>
        </u-form-item>

        <!-- 店铺Logo -->
        <u-form-item label="店铺Logo" prop="shopLogo" required borderBottom label-width="200">
          <u-upload
              accept="image"
              :fileList="fileListImage"
              @afterRead="afterRead"
              @delete="deletePic"
              name="Image"
              :multiple="false"
              :maxCount="1"
              width="200"
              height="200"
              imageMode="aspectFit"
              :disabled="viewOnly"
          >
            <view class="uploadWp" v-if="!viewOnly">
              <u-icon name="plus" color="#c9cdd4" size="60"></u-icon>
              <text style="color: #c9cdd4;font-size: 24rpx;">点击上传</text>
            </view>
          </u-upload>
        </u-form-item>

        <!-- 姓名 -->
        <u-form-item label="姓名" prop="name" required borderBottom label-width="200">
          <u--input
              v-model="formData.name"
              placeholder="请输入姓名"
              border="none"
              clearable
              :disabled="viewOnly"
          ></u--input>
        </u-form-item>

        <!-- 联系电话 -->
        <u-form-item label="联系电话" prop="phone" required borderBottom label-width="200">
          <u--input
              v-model="formData.phone"
              placeholder="请输入联系电话"
              border="none"
              clearable
              type="number"
              maxlength="11"
              :disabled="viewOnly"
          ></u--input>
        </u-form-item>

        <!-- 邮箱 -->
        <u-form-item label="邮箱" prop="mail" borderBottom label-width="200">
          <u--input
              v-model="formData.mail"
              placeholder="请输入邮箱地址"
              border="none"
              clearable
              :disabled="viewOnly"
          ></u--input>
        </u-form-item>

        <!-- 店铺地址 -->
        <!--        <u-form-item label="店铺地址"  required prop="address" borderBottom label-width="200">-->
        <!--          <u&#45;&#45;input-->
        <!--              v-model="formData.address"-->
        <!--              placeholder="请输入店铺地址"-->
        <!--              border="none"-->
        <!--              clearable-->
        <!--          ></u&#45;&#45;input>-->
        <!--        </u-form-item>-->
        <u-form-item label="店铺地址" prop="address" class='formItemWp' borderBottom
                     label-width="200"
                     @click.stop='getLocation'>
          <u-input maxlength="40" readonly v-model="formData.address" border="none"
                   placeholder='请点击选择店铺地址'
                   :disabled="viewOnly">
            <template slot="suffix" v-if="!viewOnly">
              <u-icon name="map" color="#c9cdd4" size="36"></u-icon>
            </template>
          </u-input>
        </u-form-item>

        <!-- 统一社会信用代码 -->
        <u-form-item label="信用代码" required prop="creditCode" borderBottom label-width="200">
          <u--input
              v-model="formData.creditCode"
              placeholder="请输入统一社会信用代码"
              border="none"
              clearable
              :disabled="viewOnly"
          ></u--input>
        </u-form-item>

        <!-- 注册时间 -->
        <u-form-item label="注册时间" prop="registerDate" borderBottom label-width="200">
          <!--          <u-input-->
          <!--              v-model="formData.registerDate"-->
          <!--              placeholder="请选择注册时间"-->
          <!--              border="none"-->
          <!--              readonly-->
          <!--              @click="openDate"-->
          <!--          ></u-input>-->
          <text @click="openDate" v-if="!formData.registerDate && !viewOnly" class="no-time">请选择注册时间</text>
          <text @click="openDate" v-else-if="formData.registerDate && !viewOnly" class="time-select">{{ formData.registerDate }}</text>
          <text v-else-if="viewOnly && !formData.registerDate" class="no-time">未设置</text>
          <text v-else class="time-select">{{ formData.registerDate }}</text>
        </u-form-item>

        <!-- 身份证正面 -->
        <u-form-item label="身份证正面" required prop="cardFront" label-width="200" borderBottom>
          <u-upload
              accept="image"
              :fileList="fileListCardFront"
              @afterRead="afterRead"
              @delete="deletePic"
              name="CardFront"
              :multiple="false"
              :maxCount="1"
              width="200"
              height="200"
              imageMode="aspectFit"
              :disabled="viewOnly"
          >
            <view class="uploadWp" v-if="!viewOnly">
              <u-icon name="plus" color="#c9cdd4" size="60"></u-icon>
              <text style="color: #c9cdd4;font-size: 24rpx;">点击上传</text>
            </view>
          </u-upload>
        </u-form-item>

        <!-- 身份证反面 -->
        <u-form-item label="身份证反面" required prop="cardReverse" label-width="200" borderBottom>
          <u-upload
              accept="image"
              :fileList="fileListCardReverse"
              @afterRead="afterRead"
              @delete="deletePic"
              name="CardReverse"
              :multiple="false"
              :maxCount="1"
              width="200"
              height="200"
              imageMode="aspectFit"
              :disabled="viewOnly"
          >
            <view class="uploadWp" v-if="!viewOnly">
              <u-icon name="plus" color="#c9cdd4" size="60"></u-icon>
              <text style="color: #c9cdd4;font-size: 24rpx;">点击上传</text>
            </view>
          </u-upload>
        </u-form-item>

        <!-- 营业执照 -->
        <u-form-item label="营业执照" required prop="license" borderBottom label-width="200">
          <u-upload
              accept="image"
              :fileList="fileListLicense"
              @afterRead="afterRead"
              @delete="deletePic"
              name="License"
              :multiple="false"
              :maxCount="1"
              width="200"
              height="200"
              imageMode="aspectFit"
              :disabled="viewOnly"
          >
            <view class="uploadWp" v-if="!viewOnly">
              <u-icon name="plus" color="#c9cdd4" size="60"></u-icon>
              <text style="color: #c9cdd4;font-size: 24rpx;">点击上传</text>
            </view>
          </u-upload>
        </u-form-item>
        
      </u--form>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-action" v-if="!viewOnly">
      <u-button
          :loading="loading"
          :disabled="loading"
          @click="submitForm"
          type="primary"
          size="large"
          customStyle="background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%); border: none; border-radius: 44rpx;"
      >
        {{ loading ? '提交中...' : (isNew ? '提交入驻申请' : '保存修改') }}
      </u-button>
    </view>

    <!-- 日期选择器 -->
    <u-datetime-picker
        :show="showDatePicker"
        v-model="registerDateValue"
        mode="date"
        @confirm="confirmDate"
        @cancel="showDatePicker = false"
        @close="showDatePicker = false"
    ></u-datetime-picker>
  </view>
</template>

<script>
import {mapGetters} from 'vuex'
import baseConfig from '@/config/baseUrl.js'

const chooseLocation = requirePlugin('chooseLocation');

export default {
  name: 'JoinShop',

  data() {
    return {
      isNew: true, // 判断是新入住的,还是编辑
      viewOnly: false, // 是否为只读模式
      shopInfo: {}, // 店铺信息
      loading: false,
      showDatePicker: false,
      registerDateValue: new Date().getTime(),

      // 图片文件列表
      fileListImage: [], // 店铺Logo
      fileListCardFront: [], // 身份证正面
      fileListCardReverse: [], // 身份证反面
      fileListLicense: [], // 营业执照

      formData: {
        address: '', // 店铺地址
        cardFront: '', // 身份证正面
        cardId: '', // userInfo的id
        cardReverse: '', // 身份证反面
        company: '', // 店铺名称
        coord: '', // 地址坐标
        creditCode: '', // 统一社会信用代码
        shopLogo: '', // 店铺Logo
        license: '', // 营业执照
        mail: '', // 邮箱
        name: '', // 姓名
        openId: '', // openId
        phone: '', // 联系电话
        registerDate: '', // 注册时间
        id: '',//数据的id
      },

      rules: {
        company: [
          {
            required: true,
            message: '请输入店铺名称',
            trigger: ['blur', 'change']
          }
        ],
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: ['blur', 'change']
          }
        ],
        // registerDate:[
        //   {
        //     required: true,
        //     message: '请选择注册时间',
        //     trigger: ['blur', 'change']
        //   }
        //         ],
        shopLogo: [
          {
            required: true,
            message: '请上传店铺Logo',
            trigger: ['blur', 'change']
          }
        ],
        cardFront: [
          {
            required: true,
            message: '请上传身份证正面',
            trigger: ['blur', 'change']
          }
        ],
        cardReverse: [
          {
            required: true,
            message: '请上传身份证反面',
            trigger: ['blur', 'change']
          }
        ],
        license: [
          {
            required: true,
            message: '请上传营业执照',
            trigger: ['blur', 'change']
          }
        ],
        address: [
          {
            required: true,
            message: '请输选择店铺地址',
            trigger: ['blur', 'change']
          }
        ],
        creditCode: [
          {
            required: true,
            message: '请输入统一社会信用代码',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },

  computed: {
    ...mapGetters(['userInfo', 'openId', 'wxCheckType'])
  },
  onLoad(option) {
    this.isNew = option.isNew == '1'
    this.viewOnly = option.viewOnly == 'true' // 是否为只读模式

    // 设置基本信息
    this.formData.cardId = this.userInfo?.id || ''
    this.formData.openId = this.openId || ''

    if (option.isNew != '1') {
      // 说明是编辑,需要获取店铺信息回显数据
      this._getMyShop()
    }
  },
  onShow() {
    //地图插件选点
    const location = chooseLocation.getLocation();
    if (location != null) {
      // console.log('获取地址信息', location);
      this.formData.address = location.address
      this.formData.coord = JSON.stringify(location) //发送给后台字符串
    }
  },
  onUnload() {
    // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
    chooseLocation.setLocation(null);
  },

  methods: {
    // 打开选择时间的弹窗
    openDate() {
      if (this.viewOnly) return

      console.log('点击打开注册时间', this.showDatePicker)
      this.showDatePicker = true
      console.log('点击打开注册时间2', this.showDatePicker)
    },
    // 获取我的店铺信息
    _getMyShop() {
      let params = {
        cardId: this.userInfo.id
      }
      this.$api.getMyShopInfo(params).then((res) => {
        if (res.success && res.result && res.result.records && res.result.records.length > 0) {
          this.shopInfo = res.result.records[0] || {}
          this.fillFormData()
        } else {
          this.shopInfo = {}
        }
        console.log('获取我的店铺信息', res)
      })
    },
    // 地址选点
    getLocation() {
      if (this.viewOnly) return

      const key = baseConfig.mapData.mapKey; //使用在腾讯位置服务申请的key
      const referer = baseConfig.mapData.appName //调用插件的app的名称
      const location = ''

      wx.navigateTo({
        url: `plugin://chooseLocation/index?key=${key}&referer=${referer}`
      });
    },
    // 填充表单数据
    fillFormData() {
      const info = this.shopInfo
      this.formData = {
        address: info.address || '',
        cardFront: info.cardFront || '',
        cardId: this.userInfo?.id || '',
        cardReverse: info.cardReverse || '',
        company: info.company || '',
        coord: info.coord || '',
        creditCode: info.creditCode || '',
        shopLogo: info.shopLogo || '',
        license: info.license || '',
        mail: info.mail || '',
        name: info.name || '',
        openId: this.openId || '',
        phone: info.phone || '',
        registerDate: info.registerDate || '',
        id: info.id || '',
        // remark: info.remark || ''
      }

      // 回显图片
      if (info.shopLogo) {
        this.fileListImage = [{
          url: info.shopLogo,
          status: 'success'
        }]
      }
      if (info.cardFront) {
        this.fileListCardFront = [{
          url: info.cardFront,
          status: 'success'
        }]
      }
      if (info.cardReverse) {
        this.fileListCardReverse = [{
          url: info.cardReverse,
          status: 'success'
        }]
      }
      if (info.license) {
        this.fileListLicense = [{
          url: info.license,
          status: 'success'
        }]
      }
    },

    // 确认日期选择
    confirmDate(e) {
      console.log('选择的日期:', e)
      this.formData.registerDate = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
      this.showDatePicker = false
    },

    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)

      // 同步更新表单数据
      const fieldMap = {
        'Image': 'shopLogo',
        'CardFront': 'cardFront',
        'CardReverse': 'cardReverse',
        'License': 'license'
      }

      if (fieldMap[event.name]) {
        this.formData[fieldMap[event.name]] = ''
      }
    },

    // 新增图片
    async afterRead(event) {
      console.log('新增图片', event)
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length

      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })

      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this[`fileList${event.name}`][fileListLen]

        // 生成文件名，使用当前时间戳
        const fileName = `upload_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: event.name,
          url: result,
          fileName: fileName,
          filePath: result
        }))

        // 同步更新表单数据
        const fieldMap = {
          'Image': 'shopLogo',
          'CardFront': 'cardFront',
          'CardReverse': 'cardReverse',
          'License': 'license'
        }

        if (fieldMap[event.name]) {
          this.formData[fieldMap[event.name]] = result
        }

        fileListLen++
      }
    },

    // 上传文件Promise
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: baseConfig.uploadUrl + '/casugn-system/sys/common/upload',
          filePath: url,
          name: 'file',
          success: (res) => {
            let data = JSON.parse(res.data)
            if (data.success) {
              resolve(data.message)
            } else {
              reject(new Error(data.message || '上传失败'))
            }
          },
          fail: (error) => {
            reject(error)
          }
        })
      })
    },

    // 提交表单
    async submitForm() {
      // 表单验证
      try {
        await this.$refs.form.validate()
      } catch (error) {
        console.log('表单验证失败:', error)
        return
      }

      // 检查必要的图片是否已上传
      if (!this.formData.shopLogo) {
        uni.showToast({
          title: '请上传店铺Logo',
          icon: 'none'
        })
        return
      }

      if (!this.formData.cardFront) {
        uni.showToast({
          title: '请上传身份证正面',
          icon: 'none'
        })
        return
      }

      if (!this.formData.cardReverse) {
        uni.showToast({
          title: '请上传身份证反面',
          icon: 'none'
        })
        return
      }

      if (!this.formData.license) {
        uni.showToast({
          title: '请上传营业执照',
          icon: 'none'
        })
        return
      }

      this.loading = true

      try {
        console.log('提交数据:', this.formData)
        let res = {}
        if (this.isNew) {
          res = await this.$api.addMyShop(this.formData)
        } else {
          let params = {
            ...this.formData,
            remark: "",
            status: 0,
          }
          res = await this.$api.editMyShop(params)
        }


        if (res.success) {
          uni.showToast({
            title: this.isNew ? '申请提交成功' : '修改成功',
            icon: 'none'
          })

          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: res.message || '提交失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('提交店铺信息失败:', error)
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.join-shop-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.form-container {
  flex: 1;
  background-color: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.uploadWp {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #c9cdd4;
  border-radius: 12rpx;
  background-color: #fafafa;
}

.bottom-action {
  padding: 30rpx;
  background-color: #fff;
  border-top: 2rpx solid #ebeef5;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
}

.time-select {
  color: #303133;
  font-size: 30rpx;
  text-align: left;
}

.no-time {
  color: #C0C4CD;
  font-size: 30rpx;
  text-align: left;
}

// uView 表单项样式调整
::v-deep .u-form-item {
  padding: 30rpx 24rpx;

  .u-form-item__label {
    font-size: 28rpx;
    font-weight: 500;
    color: #303133;
  }

  .u-form-item__body {
    flex: 1;
    min-width: 0;
  }
}

::v-deep .u-input {
  font-size: 28rpx;
  color: #303133;

  .u-input__content {
    .u-input__content__field-wrapper {
      .u-input__content__field-wrapper__field {
        text-align: right;
      }
    }
  }
}

::v-deep .u-textarea {
  .u-textarea__textarea {
    font-size: 28rpx;
    color: #303133;
  }
}

::v-deep .u-upload {
  .u-upload__button {
    margin-right: 0;
  }
}
</style>
